package com.deuwise.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.deuwise.common.base.Tree;
import com.deuwise.common.utils.R;
import com.deuwise.common.utils.Result;
import com.deuwise.common.validator.ValidatorUtils;
import com.deuwise.common.validator.group.AddGroup;
import com.deuwise.common.validator.group.UpdateGroup;
import com.deuwise.system.entity.DeptDO;
import com.deuwise.system.service.DeptDOService;

import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author deuwise
 * @date 2018-11-09 10:29:13
 */
@Api(tags = "部门模块", description = "部门模块")
@RequestMapping("api/deptDO")
@RestController()
public class DeptDoController extends AbstractController {
    @Autowired
    private DeptDOService deptDOService;


    @ApiOperation(value = "新增部门")
    @PostMapping()
    @RequiresPermissions("sys:dept:save")
    public R insertDept(@RequestBody DeptDO deptDO) {
        ValidatorUtils.validateEntity(deptDO, AddGroup.class);
        boolean isSuccess = false;
        if (null == deptDO) {
            return R.error(200, "新增部门失败，请稍后再试!");
        }
        deptDO.setId(null);
        int count = deptDOService.queryByName(deptDO.getName(), deptDO);
        if (count > 0) {
            return R.error(200, "部门名称不能重复");
        }
        isSuccess = deptDOService.insert(deptDO);
        if (isSuccess) {
            return R.ok(deptDO);
        } else {
            return R.error(200, "新增数据失败，请稍后再试!");
        }
    }

    /**
     * 部门信息
     */
    @GetMapping("/{deptId}")
    @RequiresPermissions("sys:dept:info")
    public Result<DeptDO> info(@PathVariable("deptId") String deptId) {
        DeptDO deptDO = deptDOService.selectById(deptId);
        return Result.ok(deptDO);
    }

    @ApiOperation("修改部门")
    @PutMapping("")
    @RequiresPermissions("sys:dept:update")
    public R update(@RequestBody DeptDO deptDO) {
        ValidatorUtils.validateEntity(deptDO, UpdateGroup.class);
        int count = deptDOService.queryByName(deptDO.getName(), deptDO);
        if (count > 0) {
            return R.error(200, "部门名称不能重复");
        }
        deptDOService.updateById(deptDO);

        return R.ok();
    }

    @ApiOperation(value = "批量删除记录")
    @RequiresPermissions("sys:dept:delete")
    @RequestMapping(value = "/deleteSelect", method = RequestMethod.POST)
    public R deleteSelect(@ApiParam(value = "ids集合", name = "ids", required = true) @RequestParam String[] ids) {
        try {
            if (ids != null && ids.length > 0) {
                deptDOService.deleteBatchIds(Arrays.asList(ids));
            }
        } catch (Exception ex) {
            return R.error("删除失败");
        }
        return R.ok();
    }

    @ApiOperation("删除部门")
    @DeleteMapping("/{deptId}")
    @RequiresPermissions("sys:dept:delete")
    public R delete(@PathVariable("deptId") String deptId) {

        //判断是否有子菜单或按钮
        List<DeptDO> menuList = deptDOService.queryListParentId(deptId);
        if (menuList.size() > 0) {
            return R.error("请先删除所有子节点");
        }

        deptDOService.deleteById(deptId);

        return R.ok();
    }

    @ApiOperation("所有部门信息")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "开始页数", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "15", dataType = "int", paramType = "query")})
    @RequiresPermissions("sys:dept:list")
    public Result<Page<DeptDO>> list( DeptDO deptDO) {
        //只有超级管理员，才能查看所有管理员列表
        Wrapper<DeptDO> wrapper = new EntityWrapper<DeptDO>();
        wrapper.orderBy("order_num",false).orderBy("id",false);
        if (deptDO != null) {
            if (StringUtils.isNotBlank(deptDO.getName())) {
                wrapper.like("name", deptDO.getName());
            }
            if (StringUtils.isNotBlank(deptDO.getParentId())) {
                wrapper.eq("parent_id", deptDO.getParentId());
            }
        }
        Page<DeptDO> page = deptDOService.selectPage(getPage(DeptDO.class), wrapper);

        return Result.ok(page);
    }

    @GetMapping("/tree")
    @ResponseBody
    @ApiOperation("查询部门树形数据")
    public R tree(DeptDO deptDO) {
        Tree<DeptDO> tree = new Tree<>();
        tree = deptDOService.getTree(deptDO);
        List<Tree<DeptDO>> treeList=new ArrayList<>();
        if(tree.getChildren()!=null){
            treeList=tree.getChildren();
        }else{
            treeList.add(tree);
        }
        return R.ok(treeList);
    }


}